import { PlusOutlined } from '@ant-design/icons';
import { FC, useRef, useState, MouseEventHandler, useEffect } from 'react';
import { Form, Select, Divider, Input, Space, Typography } from 'antd';
import { request, useApp } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { useSelectPage } from '@editor';
import { useForm } from '@formily/react';
import { random } from './utils';
import styles from './style.less';
interface FieldFormProps {
  initialValues?: any;
  // pageOutId:string
  onChange: (data: any, addList: Array<any>) => void;
  withoutForm?: boolean;
  inFormItem?: boolean;
  value?: string;
}

const FieldForm: FC<FieldFormProps> = (props) => {
  const { initialValues, onChange, withoutForm, inFormItem, value: propsValue } = props;
  const [options, $Options] = useState<Array<any>>([]);
  const [value, $Value] = useState('');
  const [validateInfo, $ValidateInfo] = useState({
    status: 'success',
    info: '',
  });
  const [form] = Form.useForm();
  const appInfo = useApp();
  const [select] = useSelectPage();
  const baseForm = useForm();
  const cacheRef = useRef(undefined);
  useEffect(() => {
    cacheRef.current = initialValues;
    form.setFieldsValue(initialValues);
  }, [initialValues]);

  useEffect(() => {
    fetchInitValue();
  }, []);

  const fetchInitValue = async () => {
    const version = InbizConfig.API_VERSION;
    const res = await request(
      `/inbiz/api/services/engines/v${version}/menuRelation/devTree?pageOutId=${select?.OutId}&type=200&siteOutId=${appInfo?.SiteInfo?.OutId}&dataVersionId=${appInfo?.DataVersionId}`,
    );
    const result =
      res?.map((ele) => ({
        label: ele?.ObjectName,
        value: ele?.OutId,
        allInfo: ele,
      })) || [];
    const selected =
      result.filter((ele) => ele?.value === initialValues || ele?.value === propsValue)[0] || {};
    $Options(result);
    onChange(selected);
  };

  const changeHandle = (value, option) => {
    const addParent = options.filter((ele) => ele.allInfo.isCreate);
    cacheRef.current = value;
    onChange(option, addParent);
  };

  const onChangeHandle = (e) => {
    $Value(e.target.value);
  };

  const addItem = (e: MouseEventHandler<HTMLAnchorElement>) => {
    const type = baseForm.query('form.senior.soure.x-component-props.sourcetype').take()! as {
      value: string;
    };
    validator()
      .then(() => {
        const middleId = random();
        const realOption = [
          ...options,
          {
            label: value,
            value: middleId,
            allInfo: {
              OutId: middleId,
              ObjectName: value,
              ObjectValue: type?.value === 'model' ? 'model' : 'custom',
              isCreate: true,
            },
          },
        ];
        const selected = realOption.filter((ele) => ele.value === cacheRef.current)[0];
        const addParent = realOption.filter((ele) => ele.allInfo.isCreate);
        onChange(selected || { allInfo: {} }, addParent);
        $Options(realOption);
        $Value('');
        $ValidateInfo({
          status: 'success',
          info: '',
        });
      })
      .catch((error) => {
        $ValidateInfo({
          status: 'error',
          info: error,
        });
      });
  };

  const dropDownRender = (menu) => {
    return (
      <>
        {menu}
        <Divider style={{ margin: '8px 0' }} />
        <Space align="center" style={{ padding: '0 8px 4px' }}>
          <Input value={value} onChange={onChangeHandle} status={validateInfo.status} />
          <Typography.Link onClick={addItem} style={{ whiteSpace: 'nowrap' }}>
            <PlusOutlined /> <TextWidget>AuthForm.add</TextWidget>
          </Typography.Link>
        </Space>
        {validateInfo.status === 'error' && (
          <span style={{ color: 'red', fontSize: '12px', padding: '0 8px 4px', display: 'block' }}>
            {validateInfo.info}
          </span>
        )}
      </>
    );
  };

  const validator = () => {
    const hasOption = options.some((ele) => ele.label === value);
    if (hasOption) {
      return Promise.reject(getMessage('AuthForm.message.hasGorup'));
    } else if (!value || value.length === 0) {
      return Promise.reject(getMessage('AuthForm.message.notEmpty'));
    }
    return Promise.resolve();
  };

  const onSelect = () => {
    $Value('');
    $ValidateInfo({
      status: 'success',
      info: '',
    });
  };

  const changeValidateStatus = () => {
    $ValidateInfo({
      status: 'success',
      info: '',
    });
  };

  return withoutForm ? (
    inFormItem ? (
      <Select
        options={options}
        onSelect={onSelect}
        onChange={changeHandle}
        value={options?.length ? propsValue : undefined}
        allowClear
        dropdownRender={dropDownRender}
        onDropdownVisibleChange={changeValidateStatus}
      />
    ) : (
      <Form.Item
        label={<TextWidget>AuthForm.authgroup</TextWidget>}
        name="auth"
        className={styles['auth']}
        style={{ display: 'inline-flex', width: '38%', margin: '0 24px 0 0' }}
      // validateStatus={validateInfo.status}
      // help={validateInfo.info}
      >
        <Select
          options={options}
          onSelect={onSelect}
          onChange={changeHandle}
          value={value}
          allowClear
          dropdownRender={dropDownRender}
          onDropdownVisibleChange={changeValidateStatus}
        />
      </Form.Item>
    )
  ) : (
    <Form
      form={form}
      initialValues={{ auth: initialValues }}
      colon={false}
      className={styles['auth']}
      labelCol={{ span: 8 }}
      labelAlign="left"
    >
      <Form.Item
        label={<TextWidget>AuthForm.authgroup</TextWidget>}
        name="auth"
        style={{ display: 'inline-flex', width: '38%', marginRight: '24px', marginBottom: 0 }}
      >
        <Select
          options={options}
          onSelect={onSelect}
          onChange={changeHandle}
          allowClear
          dropdownRender={dropDownRender}
          onDropdownVisibleChange={changeValidateStatus}
        />
      </Form.Item>
    </Form>
  );
};

export default FieldForm;
